package udp2;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;

import javax.swing.*;

public class DatagramPacketTestUDP2 extends JFrame implements Runnable,ActionListener {
	Container con = getContentPane();
	JPanel jp = new JPanel();
	JButton jb1 = new JButton("接收");
	JButton jb2 = new JButton("断开");
	JTextArea test1 = new JTextArea();
	JTextArea test2 = new JTextArea();
	InetAddress net = null;
	int port = 9999;
	
	MulticastSocket socket = null;
	Thread thread=null;
	Boolean b=false;

	public DatagramPacketTestUDP2() {
		thread=new Thread(this);
		jb1.addActionListener(this);
		jb2.addActionListener(this);
		
		setVisible(true);
		con.setBackground(Color.cyan);
		setLayout(null);
		setTitle("多点广播接收系统");
		setBounds(400, 300, 800, 500);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		jp.setLayout(null);
		jp.add(jb1);
		jb1.setBounds(320, 20, 70, 30);
		con.add(jb2);
		jb2.setBounds(420, 20, 70, 30);
		jp.setBackground(Color.darkGray);
		con.add(jp);
		jp.setBounds(0, 0, 800, 100);// 面板位置与大小

		con.add(test1);
		test1.setBounds(20, 100, 350, 322);
		con.add(test2);
		test2.setBounds(400, 100, 350, 322);
		
		validate();
		
		try {
			net = InetAddress.getByName("224.0.4.0");
			socket = new MulticastSocket(port);
			socket.joinGroup(net);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		while (true) {
				byte[] a = new byte[1024];
				DatagramPacket  packet = new DatagramPacket(a, a.length, net, port);
				try {
				socket.receive(packet);
				String about=new String(packet.getData(),0,packet.getLength());
				test1.setText("正在接收:\n"+about);
				test2.append(about+"\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(b==true) {
				break;
			}
		}
	}
	public void actionPerformed(ActionEvent e)  {
		if(e.getSource()==jb1) {
			jb1.setBackground(Color.red);
			jb2.setBackground(Color.white);
			if(!(thread.isAlive())) {
			 thread=new Thread(this);
			}
			thread.start();
			b=false;
		}
		if(e.getSource()==jb2) {
			jb1.setBackground(Color.white);
			jb2.setBackground(Color.red);
			/*try {
			thread.interrupt();
			}catch(Exception w) {
				test1.append("停止收听");
			}
			*/
			b=true;
		}
	}
	

	public static void main(String[] args) {
		DatagramPacketTestUDP2 man=new DatagramPacketTestUDP2();
	}

}
